<?php

function kq_ck_null($kq_va,$kq_na) {
    if($kq_va == "") {
      $kq_va="";
    } else {
      return $kq_va=$kq_na.'='.$kq_va.'&';
    }
}

class ControllerPaymentKuaiqianmobile extends Controller {

  const merchantAcctId = '1007883177601';

  function test() {
    $ss = $this->buildReqest(2018, 20872639872938, 'http://www.bing.com');
    echo $ss;
  }

  public function buildReqest($amount, $orderId, $bgUrl) {
    $kq_target="https://www.99bill.com/mobilegateway/recvMerchantInfoAction.htm";
    $kq_merchantAcctId = ControllerPaymentKuaiqianmobile::merchantAcctId;;   //*  商家用户编号     (30)

    $kq_inputCharset    = "1";  //   1 ->  UTF-8        2 -> GBK        3 -> GB2312   default: 1    (2)
    $kq_pageUrl     = $this->url->link('checkout/success'); //   直接跳转页面 (256)
    $kq_bgUrl       = $bgUrl; //   后台通知页面 (256)
    $kq_version     = "mobile1.0";  //*  版本  固定值 v2.0   (10)
    $kq_language        = "1";  //*  默认 1 ， 显示 汉语   (2)
    $kq_signType        = "4";   //*  固定值 1 表示 MD5 加密方式 , 4 表示 PKI 证书签名方式   (2)

    $kq_payerName       = ""; //   英文或者中文字符   (32)
    $kq_payerContactType = "1";  //  支付人联系类型  固定值： 1  代表电子邮件方式 (2)
    $kq_payerContact   = "";    //   支付人联系方式    (50)
    $kq_orderId     = $orderId; //*  字母数字或者, _ , - ,  并且字母数字开头 并且在自身交易中式唯一  (50)
    $amount2 = (float)$amount;
    $amount2 = number_format($amount2*100,0,'.','');
    $orderAmount = $amount2;
    $kq_orderAmount = $orderAmount; //*   字符金额 以 分为单位 比如 10 元， 应写成 1000 (10)
    $kq_orderTime       = date('YmdHis');  //*  交易时间  格式: 20110805110533
    $kq_productName = "百货栈订单".$orderId;   //    商品名称英文或者中文字符串(256)
    $kq_productNum      = "";   //    商品数量  (8)
    $kq_productId       = "";   //    商品代码，可以是 字母,数字,-,_   (20) 
    $kq_productDesc = ""; //    商品描述， 英文或者中文字符串  (400)
    $kq_ext1            = "";   //    扩展字段， 英文或者中文字符串，支付完成后，按照原样返回给商户。 (128)
    $kq_ext2            = "";
    $kq_payType     = "21"; //*  固定选择值：00、15、21、21-1、21-2
    //00代表显示快钱各支付方式列表；
    //15信用卡无卡支付
    //21 快捷支付
    //21-1 代表储蓄卡快捷；21-2 代表信用卡快捷
    //*其中”-”只允许在半角状态下输入。

    $kq_bankId          = "";   // 银行代码 银行代码 要在开通银行时 使用， 默认不开通 (8)
    $kq_redoFlag        = "1";   // 同一订单禁止重复提交标志  固定值 1 、 0      
                            // 1 表示同一订单只允许提交一次 ； 0 表示在订单没有支付成功状态下 可以重复提交； 默认 0 
    $kq_pid         = "";   //  合作伙伴在快钱的用户编号 (30)
    $kq_payerIdType="";    //指定付款人
    $kq_payerId=""; //付款人标识


    $kq_all_para=kq_ck_null($kq_inputCharset,'inputCharset');
    $kq_all_para.=kq_ck_null($kq_pageUrl,"pageUrl");
    $kq_all_para.=kq_ck_null($kq_bgUrl,'bgUrl');
    $kq_all_para.=kq_ck_null($kq_version,'version');
    $kq_all_para.=kq_ck_null($kq_language,'language');
    $kq_all_para.=kq_ck_null($kq_signType,'signType');
    $kq_all_para.=kq_ck_null($kq_merchantAcctId,'merchantAcctId');
    $kq_all_para.=kq_ck_null($kq_payerName,'payerName');
    $kq_all_para.=kq_ck_null($kq_payerContactType,'payerContactType');
    $kq_all_para.=kq_ck_null($kq_payerContact,'payerContact');
    $kq_all_para.=kq_ck_null($kq_payerIdType,'payerIdType');
    $kq_all_para.=kq_ck_null($kq_payerId,'payerId');
    $kq_all_para.=kq_ck_null($kq_orderId,'orderId');
    $kq_all_para.=kq_ck_null($kq_orderAmount,'orderAmount');
    $kq_all_para.=kq_ck_null($kq_orderTime,'orderTime');
    $kq_all_para.=kq_ck_null($kq_productName,'productName');
    $kq_all_para.=kq_ck_null($kq_productNum,'productNum');
    $kq_all_para.=kq_ck_null($kq_productId,'productId');
    $kq_all_para.=kq_ck_null($kq_productDesc,'productDesc');
    $kq_all_para.=kq_ck_null($kq_ext1,'ext1');
    $kq_all_para.=kq_ck_null($kq_ext2,'ext2');
    $kq_all_para.=kq_ck_null($kq_payType,'payType');
    $kq_all_para.=kq_ck_null($kq_bankId,'bankId');;
    $kq_all_para.=kq_ck_null($kq_redoFlag,'redoFlag');
    $kq_all_para.=kq_ck_null($kq_pid,'pid');

  //$kq_all_para=substr($kq_all_para,0,strlen($kq_all_para)-1);
  //$kq_all_para=substr($kq_all_para,0,-1);
    $kq_all_para=rtrim($kq_all_para,'&');
    // echo $kq_all_para;
  //////////////////////////////               lib  start  
  ////////  私钥加密 生成 MAC
    $priv_key = file_get_contents(DIR_SYSTEM . "library/cert/99bill-rsa.pem");
    $pkeyid = openssl_get_privatekey($priv_key);
  //  echo '$pkeyid='.$pkeyid.'<br>';
    // compute signature
    openssl_sign($kq_all_para, $signMsg, $pkeyid);
    // free the key from memory
    openssl_free_key($pkeyid);
    $kq_sign_msg = base64_encode($signMsg);
    // echo $kq_sign_msg;
    ///////////
    //////////////////////////////               lib  end
    $kq_get_url=$kq_target.'?'.$kq_all_para.'&signMsg='.$kq_sign_msg;


    $sHtml = '<form method=get name="kqMPay" action="' . $kq_target .'">
  <input type="hidden" name="inputCharset" value="' . $kq_inputCharset .'">
  <input type="hidden" name="pageUrl" value="' . $kq_pageUrl .'">
  <input type="hidden" name="bgUrl" value="' . $kq_bgUrl .'">
  <input type="hidden" name="version" value="' . $kq_version .'">
  <input type="hidden" name="language" value="' . $kq_language .'">
  <input type="hidden" name="signType" value="' . $kq_signType .'">
  <input type="hidden" name="merchantAcctId" value="' . $kq_merchantAcctId .'">
  <input type="hidden" name="payerName" value="' . $kq_payerName .'">
  <input type="hidden" name="payerContactType" value="' . $kq_payerContactType .'">
  <input type="hidden" name="payerContact" value="' . $kq_payerContact .'">
  <input type="hidden" name="payerIdType" value="' . $kq_payerIdType .'">
  <input type="hidden" name="payerId" value="' . $kq_payerId .'">
  <input type="hidden" name="orderId" value="' . $kq_orderId .'">
  <input type="hidden" name="orderAmount" value="' . $kq_orderAmount .'">
  <input type="hidden" name="orderTime" value="' . $kq_orderTime .'">
  <input type="hidden" name="productName" value="' . $kq_productName .'">
  <input type="hidden" name="productNum" value="' . $kq_productNum .'">
  <input type="hidden" name="productId" value="' . $kq_productId .'">
  <input type="hidden" name="productDesc" value="' . $kq_productDesc .'">
  <input type="hidden" name="ext1" value="' . $kq_ext1 .'">
  <input type="hidden" name="ext2" value="' . $kq_ext2 .'">
  <input type="hidden" name="payType" value="' . $kq_payType .'">
  <input type="hidden" name="bankId" value="' . $kq_bankId .'">
  <input type="hidden" name="redoFlag" value="' . $kq_redoFlag .'">
  <input type="hidden" name="pid" value="' . $kq_pid .'">
  <input type="hidden" name="signMsg" value="' . $kq_sign_msg .'">
  <input type="submit" value="SUBMIT" name="go_pay" style="font-size:32px;padding:10px;font-weight:bold;font-family:arail;display:none;">
</form>';
    
    $sHtml = $sHtml."<script>document.forms['kqMPay'].submit();</script>";
    return $sHtml;
  }

  public function index() {
    $this->load->model('checkout/order');

    $order_id = $this->session->data['order_id'];

    $order_info = $this->model_checkout_order->getOrder($order_id);
    
    $this->load->model('account/order');

    $shipping_cost = 0;

    $totals = $this->model_account_order->getOrderTotals($order_id);

    foreach ($totals as $total) {
      
      if($total['title'] == 'shipping') {
        
        $shipping_cost = $total['value'];
        
      }
      
    }
    

        $payment_type = "1";

        $notify_url = HTTPS_SERVER.'catalog/controller/payment/kuaiqianmobile_callback.php';

        // $return_url = $this->url->link('common/pc') . '#/payment/return';

        $seller_email = $this->config->get('kuaiqianmobile_seller_email');

        $out_trade_no = $this->session->data['order_id'];

        $subject = $item_name . ' ' . $this->language->get('text_order') .' '. $order_id;

        $amount = $order_info['total'];
    
    $currency_value = $this->currency->getValue('CNY');
    $price = $amount * $currency_value;
    $price = number_format($price,2,'.','');
    
    $total_fee = $price;

    $data['html_text'] = $this->buildReqest($total_fee, $order_id, $notify_url);
    
    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/kuaiqianmobile.tpl')) {
      return $this->load->view($this->config->get('config_template') . '/template/payment/kuaiqianmobile.tpl', $data);
    } else {
      return $this->load->view('default/template/payment/kuaiqianmobile.tpl', $data);
    }
    
  }
  
  public function callback() {
    $kq_check_all_para=kq_ck_null($_GET['merchantAcctId'],'merchantAcctId').kq_ck_null($_GET['version'],'version').kq_ck_null($_GET['language'],'language').kq_ck_null($_GET['signType'],'signType').kq_ck_null($_GET['payType'],'payType').kq_ck_null($_GET['bankId'],'bankId').kq_ck_null($_GET['orderId'],'orderId').kq_ck_null($_GET['orderTime'],'orderTime').kq_ck_null($_GET['orderAmount'],'orderAmount').kq_ck_null($_GET['bindCard'],'bindCard').kq_ck_null($_GET['bindMobile'],'bindMobile').kq_ck_null($_GET['dealId'],'dealId').kq_ck_null($_GET['bankDealId'],'bankDealId').kq_ck_null($_GET['dealTime'],'dealTime').kq_ck_null($_GET['payAmount'],'payAmount').kq_ck_null($_GET['fee'],'fee').kq_ck_null($_GET['ext1'],'ext1').kq_ck_null($_GET['ext2'],'ext2').kq_ck_null($_GET['payResult'],'payResult').kq_ck_null($_GET['errCode'],'errCode');

    $trans_body=substr($kq_check_all_para,0,strlen($kq_check_all_para)-1);
    $MAC=base64_decode($_GET['signMsg']);

    //$fp = fopen("./99bill[1].cert.rsa.20140728.cer", "r"); 
    //$cert = fread($fp, 8192); 
    //fclose($fp); 

    $cert = file_get_contents(DIR_SYSTEM . "library/cert/99bill.cert.rsa.20340630.cer");
    $pubkeyid = openssl_get_publickey($cert); 
    $verify_result = openssl_verify($trans_body, $MAC, $pubkeyid); 
    // $verify_result = true;

    $log = false;

    if($log) {
      $this->log->write('Kuaiqian_Mobile :: Two: ' . $verify_result);
    }
    
    if($verify_result) {
          
      $out_trade_no = $_GET['orderId'];
      
      $order_id   = $out_trade_no; 
      
      $order_status_id = $this->config->get('config_order_status_id');
      
      $this->load->model('checkout/order');

      $order_info = $this->model_checkout_order->getOrder($order_id);
      
      if($log) {
        $this->log->write('Kuaiqian_Mobile :: Three: ');
      }
      
      if ($order_info) {
        
        if($log) {
          $this->log->write('Kuaiqian_Mobile :: Four: ');
        }
        
      
        if($_GET['payResult']=='10') {
        
          if($log) {
            $this->log->write('Kuaiqian_Mobile :: Five: ');
          }

          $rtnUrl = $this->url->link('checkout/success');
          // $rtnUrl = $this->url->link('common/pc') . '#/payment/return?';
          $success_rtn = '<result>1</result> <redirecturl>'.$rtnUrl.'</redirecturl>';
        
          $order_status_id = $this->config->get('kuaiqianmobile_order_status_id');
          
          $this->model_checkout_order->setIsPay($order_id);

          $res = $this->model_checkout_order->getOrderById($order_id);
                                        
          $this->model_checkout_order->updatemoney($res,$order_id);
          if (!$order_info['order_status_id']) {
            
            $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, '', true);
            
          } else {
            
            $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, '', true);
            
          }
        
            
          echo $success_rtn; 
      
        }
        
        //清除sesssion，避免客户返回不到成功页面而无法清除原有的购物车等信息
        $this->cart->clear();
        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['payment_methods']);
        unset($this->session->data['guest']);
        unset($this->session->data['comment']);
        unset($this->session->data['order_id']);
        unset($this->session->data['coupon']);
        unset($this->session->data['reward']);
        unset($this->session->data['voucher']);
        unset($this->session->data['vouchers']);
        unset($this->session->data['totals']);
        
      }else{
        
        if($log) {
          $this->log->write('Kuaiqian_Mobile :: Seven: ');
        }
        
        echo "fail";
        
      }
      
    } else {
      
      if($log) {
        $this->log->write('Kuaiqian_Mobile :: Eight: ');
      }
      
      echo "fail";
    
    }    
  }
}